package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.util.DataBackupUtil;
import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.util.PageResult;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("permission")
public class PermissionController {

    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("view")
    @RequiresPermissions(value = {"permission:view","权限页面"},logical = Logical.OR)
    public String view() throws Exception{

        return "permission/permission";
    }

    @RequestMapping("selectAll")
    @ResponseBody
    public List<Permission> selectAll() throws Exception{
        return permissionService.selectAll();
    }

    @RequestMapping("selected")
    @ResponseBody
    public List<Permission> selected(Long id) throws Exception{
        return permissionService.selectPermissionByRoleId(id);
    }

    @RequestMapping("load")
    @ResponseBody
    @RequiresPermissions(value = {"permission:load","权限加载"},logical = Logical.OR)
    public JsonResult load() throws Exception{
        JsonResult jsonResult = new JsonResult();
        try{
            permissionService.load();
        }catch (Exception e){
            jsonResult.mark("操作失败");
        }
        return jsonResult;
    }
    @RequestMapping("delete")
    @ResponseBody
    @RequiresPermissions(value = {"permission:delete","权限删除"},logical = Logical.OR)
    public JsonResult delete(Long id) throws Exception{
        JsonResult jsonResult = new JsonResult();
        try{
            permissionService.deleteByPrimaryKey(id);
        }catch (Exception e){
            jsonResult.mark("操作失败");
        }
        return jsonResult;
    }

    @RequestMapping("list")
    @ResponseBody
    public PageResult list(QueryObject qo) throws Exception{
        return permissionService.query(qo);
    }


    @RequestMapping("databackup")
    @ResponseBody
    public JsonResult databackup(){
        JsonResult result = new JsonResult();
        try {
            DataBackupUtil.backup();
        } catch (Exception e) {
            result.mark(e.getMessage());
        }
        return  result;
    }
}
